<script lang="ts" setup>
import type { VbenFormSchema } from '@vben/common-ui';
import type { Recordable } from '@vben/types';

import { computed, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElButton } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';

import { useVbenForm, z } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { validatePasswordResetApi } from '#/api/core/auth';

defineOptions({ name: 'ResetPassword' });

const router = useRouter();
const route = useRoute();
const loading = ref(false);
const token = ref('');

// 在组件挂载时获取URL中的token参数
onMounted(() => {
  // 从URL参数中获取token
  const tokenParam = route.query.token as string;
  if (!tokenParam) {
    ElMessage.error($t('authentication.invalidResetToken'));
    // 无效的重置链接，跳转到忘记密码页面
    setTimeout(() => {
      router.push('/auth/forget-password');
    }, 1500);
  } else {
    token.value = tokenParam;
  }
});

// 密码表单定义
const formSchema = computed((): VbenFormSchema[] => {
  return [
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: $t('authentication.newPasswordPlaceholder'),
        type: 'password',
        autocomplete: 'new-password',
      },
      fieldName: 'newPassword',
      label: $t('authentication.newPassword'),
      rules: z
        .string()
        .min(6, { message: $t('authentication.passwordMinLength') })
        .regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()]).+$/, {
          message: $t('authentication.passwordComplexity'),
        }),
    },
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: $t('authentication.confirmPasswordPlaceholder'),
        type: 'password',
        autocomplete: 'new-password',
      },
      fieldName: 'confirmPassword',
      label: $t('authentication.confirmPassword'),
      rules: z
        .string()
        .min(1, { message: $t('authentication.confirmPasswordRequired') }),
    },
  ];
});

// 创建表单
const [Form, formApi] = useVbenForm(
  reactive({
    commonConfig: {
      hideLabel: true,
      hideRequiredMark: true,
    },
    schema: computed(() => formSchema.value),
    showDefaultActions: false,
  }),
);

/**
 * 处理表单提交
 */
async function handleSubmit() {
  const { valid } = await formApi.validate();
  if (!valid) return;

  const values = await formApi.getValues();

  if (!token.value) {
    ElMessage.error($t('authentication.invalidResetToken'));
    return;
  }

  // 直接比较表单提交的值
  if (values.newPassword !== values.confirmPassword) {
    console.log('密码不一致:', values.newPassword, values.confirmPassword);
    ElMessage.error($t('authentication.passwordMismatch'));
    return;
  }

  try {
    loading.value = true;

    // 调用密码重置验证接口
    await validatePasswordResetApi({
      token: token.value,
      newPassword: values.newPassword,
      resetType: 1, // Email方式 (后端枚举值)
    });

    // 请求成功
    ElMessage.success($t('authentication.passwordResetSuccess'));

    // 重定向回登录页
    setTimeout(() => {
      router.push('/auth/login');
    }, 1500);
  } catch (error: any) {
    // 请求失败处理
    const message = error.response?.data?.message || $t('authentication.passwordResetFailed');
    ElMessage.error(message);
  } finally {
    loading.value = false;
  }
}

/**
 * 返回登录页
 */
function goToLogin() {
  router.push('/auth/login');
}
</script>

<template>
  <div class="reset-password-container">
    <!-- 标题 -->
    <div class="title-area">
      <h2 class="title">{{ $t('authentication.resetPassword') }}</h2>
      <p class="subtitle">{{ $t('authentication.resetPasswordDesc') }}</p>
    </div>

    <!-- 表单 -->
    <Form />

    <!-- 按钮区域 -->
    <div class="button-area">
      <ElButton
        type="primary"
        :loading="loading"
        class="submit-button"
        @click="handleSubmit"
      >
        {{ $t('authentication.submitNewPassword') }}
      </ElButton>

      <ElButton
        plain
        class="back-button"
        @click="goToLogin"
      >
        {{ $t('common.back') }}
      </ElButton>
    </div>
  </div>
</template>

<style scoped>
.reset-password-container {
  width: 100%;
  max-width: 420px;
  margin: 0 auto;
  padding: 24px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

.title-area {
  margin-bottom: 24px;
  text-align: center;
}

.title {
  font-size: 24px;
  font-weight: 700;
  margin-bottom: 8px;
}

.subtitle {
  font-size: 14px;
  color: #6b7280;
}

.button-area {
  margin-top: 24px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.submit-button, .back-button {
  width: 100%;
  height: 40px;
  font-size: 14px;
  margin-left: 0px;
}
</style>
